pvp = LibStub("AceAddon-3.0"):NewAddon("PvPness2","AceConsole-3.0","AceEvent-3.0")
wsg = pvp:NewModule("wsg","AceEvent-3.0")
--ab = pvp:NewModule("ab","AceEvent-3.0")
--bfg = pvp:NewModule()

-- ideas:
-- for ToK, set initial info box to corner that orb is located (red = NW, orange = NE, green = SW, blue = SE)


--useful in game stuff
-- /framestack
-- /eventtrace

COLORS = {}
for p in pairs(RAID_CLASS_COLORS) do
    COLORS[p] = RAID_CLASS_COLORS[p]
end
COLORS["gray"] = { r=153/255, g=153/255, b=153/255}
COLORS["black"] = { r=0, g=0, b=0}
COLORS["white"] = { r=1, g=1, b=1}
COLORS["Horde"] = {r=240/255, g=30/255, b=20/255}
COLORS["Alliance"] = {r=0, g=180/255, b=240/255}


do
	local zonedinto
	local bgTable = { 
		["Warsong Gulch"] = wsg,
		["Twin Peaks"] = wsg,
		--["Arathi Basin"] = ab,
	}
	local classes
	local specs

	
	
--------------------------------------------------------------------------------------------------
    local function CreateButton(frame)
	--[[
		create the spy button; maybe other buttons at some point?
	--]]
        local button = CreateFrame("Frame",nil,frame)
        button:SetFrameStrata("BACKGROUND")
        button:SetPoint("TOPRIGHT",0,0)
        button:SetScript("OnMouseDown",function(self,mouseButton) pvp:Spy(mouseButton) end)
 
        local buttonText = button:CreateFontString(nil,"ARTWORK")
        buttonText:SetTextColor(1,1,1)
        buttonText:SetAllPoints()
        buttonText:SetFont(pvp.settings.all.font.path,12,"OUTLINE")
        buttonText:SetText("-SPY-")		
				
		button:SetWidth( buttonText:GetStringWidth() + 2)
		button:SetHeight( buttonText:GetStringHeight() + 2)
		
		button.text = buttonText
		
		button:SetScript("OnEnter",
			function(b)
				b.text:SetTextColor(1,0,0)
			end
		)
		button:SetScript("OnLeave",
			function(b)
				b.text:SetTextColor(1,1,1)
			end
		)
 
        button:Show()
 
        return button
    end

--------------------------------------------------------------------------------------------------
    local function CreateBar(frame, id, target)
    --[[
		create and return a new frame that consists of two parts: info and status
	--]]
        local base --containing frame
        if target then
            base = CreateFrame("Button",nil,frame,"SecureUnitButtonTemplate")
            SecureUnitButton_OnLoad(base,target,nil)
        else
            base = CreateFrame("Frame",nil,frame)
        end 
        
        base.id = id --store the number of this bar for easier bookkeeping/access

        base:SetFrameStrata("BACKGROUND")
        base:SetPoint("TOPLEFT",0,0)
        --info box
        local info = CreateFrame("StatusBar",nil,base)
        info:SetPoint("TOPLEFT",0,0)
        info.text = info:CreateFontString(nil,"ARTWORK")
        info.text:SetAllPoints()
        --status bar
        local status = CreateFrame("StatusBar",nil,base)
        status:SetPoint("TOPRIGHT",0,0)
        status.text = status:CreateFontString(nil,"ARTWORK")
        status.text:SetAllPoints()
        --attach to base
        base.info = info
        base.status = status
 
        return base
    end
 
--------------------------------------------------------------------------------------------------
    local function main()
	--[[
		setup up the main frame with all the bars and stuff
		called by OnEnable
	--]]
        if pvp.frame then --avoid duplication
            if not pvp.frame:IsVisible() then
                pvp.frame:Show()
            end
            return
        end
 
        --main frame
        local frame = CreateFrame("Frame","main",UIParent)  
        frame:SetFrameStrata("BACKGROUND")
        frame.background = frame:CreateTexture(nil,"BACKGROUND")
        frame.background:SetAllPoints()
        frame.title = frame:CreateFontString(nil,"ARTWORK")
        frame.title:SetPoint("TOP",0,-1)
		
		frame.spy = CreateButton(frame)
        
        frame.bars = {} --create all bars that will ever be used on start, but only show when needed
        
		--setup alpha stuff because some guy asked for it 
        frame.mouseover = false
        local enter =
            function()
                local pvp = pvp
                pvp.frame.mouseover = true
                pvp.frame:SetScript("OnUpdate",nil)
                pvp.frame:SetAlpha(pvp.settings.alpha.mouse)
            end
        local leave =  
            function()
                local t0 = GetTime()
                local pvp = pvp
                pvp.frame:SetScript("OnUpdate",
                    function(f)
                        if GetTime() >= t0 + pvp.settings.alpha.fade then
                            pvp.frame.mouseover = false
                            pvp:Alpha()
                            f:SetScript("OnUpdate",nil)
                        end
                    end
                )
            end          
        frame:SetScript("OnEnter",enter)
        frame:SetScript("OnLeave",leave)
        pvp:RegisterEvent("PLAYER_REGEN_DISABLED","Alpha")
        pvp:RegisterEvent("PLAYER_REGEN_ENABLED","Alpha")         
 
        --bars 1 - 4 are secure frames
        for i=1,4 do
            local bar = CreateBar(frame,i,"arena"..i)          
            bar:SetScript("OnEnter",enter)
            bar:SetScript("OnLeave",leave)          
            bar:Hide()
            frame.bars[i] = bar
        end
 
        --bar 5 - 15 are normal frames
        for i=5,15 do
            local bar = CreateBar(frame,i)
            bar:SetScript("OnEnter",enter)
            bar:SetScript("OnLeave",leave)
            bar:Hide()
            frame.bars[i] = bar
        end
    
        pvp.frame = frame
        pvp.mode = "all"
		
		--run through all the appearance functions
        pvp:ToggleMove()      
        pvp:Resize()
        pvp:Redraw()
        pvp:Alpha()      
    end

--------------------------------------------------------------------------------------------------
	function pvp:DefaultClickText(bar)
	--[[
		set a default message that will broadcast when right clicking a bar
	--]]
        if not bar then return end  

        bar:SetScript("OnMouseDown",
            function(self,button)
                if button == "RightButton" then
                    local info = self.info.text:GetText()
                    local status = self.status.text:GetText()
                    if info then
                        --SendChatMessage(format("%s - %s",info,status), "SAY")
						pvp:Broadcast(format("%s - %s",info,status))
                    else
                        --SendChatMessage(status,"SAY")
						pvp:Broadcast(status)
                    end
                end
            end
        )
    end	

--------------------------------------------------------------------------------------------------
	function pvp:Broadcast(str)
	--[[ 
		iterate through chat channels and print messages to each 
	--]]
		if not str or str == "" then return end
		local channels = pvp.settings.broadcast
		for i,p in ipairs(channels) do
			SendChatMessage(str,p)
		end
	end
	
--------------------------------------------------------------------------------------------------
	function pvp:FormatText(t,keys)
	--[[
		substitutes parameters in table 'keys' into format string stored in table 't'
		returns the formatted string complete with substitutions
	--]]
		local params = {}
		for i,p in ipairs(t[2]) do
			local key,case = strmatch(p,"(%a+)([%+%-]?)")
			key = keys[key] or "nil" --nil means it was a bad key name
			if case == "+" then
				key = strupper(key)
			elseif case == "-" then
				key = strlower(key)
			end
			tinsert(params,key)
		end

		return format(t[1],unpack(params))
	end
	
--------------------------------------------------------------------------------------------------
	function pvp:Parse(str)
	--[[
		parses input from a textbox and parses into component format string and a table of parameters
		returns a table containing the format string and the parameter table or nil if bad string
	--]]
	
		str = str.."," --str requires a comma at the end for all the formatting goodness to work
		
		local fstr,pstr = strmatch(str,"\"(.+)\",(.*)")	   
		if not fstr then return nil end
	   
		local params = {}
		local pos = 1		
		while(pos < #(pstr)) do
			local _,pos2,key = strfind(pstr,"(.-),",pos)
			tinsert(params,key)
			pos = pos2+1 --move past key and comma
		end
		
		pos = 1
		local sCount = 0
		while(pos < #(fstr)) do
			local _,pos2 = strfind(fstr,"%%s",pos)
			sCount = sCount + 1
			pos = pos2+1
		end
		--can't have more %s than keys
		if sCount > #(params) then return nil end
	   
		return { fstr, params } --store a table in settings
	end
	
--------------------------------------------------------------------------------------------------
	function pvp:Unparse(t)
	--[[
		take the table stored in settings and convert it back into a string to display in options menu
	--]]
		local pstr = ""
		local count = #(t[2])
		for i,p in ipairs(t[2]) do
			pstr = pstr..p
			if i < count then pstr = pstr.."," end
		end

		return format("\"%s\",%s",t[1],pstr)
	end
	
--------------------------------------------------------------------------------------------------
	function pvp:TestInput(msg)
	--[[
		tests any user input for proper parameter names
		prints test message to chatframe
	--]]
		pvp:Print("|cffffcc00Message preview|r")
		pvp:Print(msg)
		if strmatch(msg,"nil") then
			pvp:Print("|cffffcc33Note:|r If you see an unintended |cffff0000nil|r in your message, a key you have entered is not available.")
		end
	end



--------------------------------------------------------------------------------------------------
    function pvp:SetBarAsTimer(bar,t0,t1)
	--[[
		sets a bar to do an animated countdown
		t0 is is the the max timer
		t1 is optional, sets the current time of the bar
	--]]
        if not bar then return end
		
        bar.status:SetMinMaxValues(0,t0)
        bar.status:SetValue(t1 or t0) --create timer in progress (ex: time to win)
        bar.status.endTime = GetTime() + (t1 or t0) --when this timer ends
        bar.status:SetScript("OnUpdate",
            function(self)
                local currentTime = GetTime()
                local parent = self:GetParent()
                local info = parent.info
              
                if currentTime < self.endTime then
                    local t = floor(self.endTime) - floor(currentTime) --ignore milli precision
                    local m = floor(t/60)
                    local s = strmatch( format('%.2f',(t%60)/100), "0%.(%d+)" )                  
                    info.text:SetText(m..":"..s)
                    self:SetValue(self.endTime - currentTime) --keep milli precision here for smoother countdown
                else
                    pvp:Stop(parent) --the script is only running on the status portion of the bar
                    if parent.func then
                        parent:func(parent)
                    end
                end
            end
        )
    end  
  
--------------------------------------------------------------------------------------------------
    function pvp:Stop(bar)
	--[[
		stop a bar countdown
	--]]
        --if not bar then return end      
        bar.status:SetScript("OnUpdate",nil)
        bar.status:SetMinMaxValues(0,1)
        bar.status:SetValue(1)
        bar.info.text:SetText("")      
    end



--------------------------------------------------------------------------------------------------
    function pvp:ShowFrames(count,secure)
	--[[
		show 'count' number of bars; use secure frames if 'secure' is true
		returns the bars that were shown
	--]]
        local frame = pvp.frame
        local returnTable = {}
        local indexMin = (secure and 1) or 5
        local indexMax = (secure and count) or (4 + count) --for loop adjustment
        for i=indexMin,indexMax do
            pvp:Log("Showing bar "..i) 
            local bar = frame.bars[i]  
            bar:Show()
            tinsert(returnTable,bar)
        end
        return unpack(returnTable)
    end

--------------------------------------------------------------------------------------------------
    function pvp:Reset()
	--[[
		reset all the various things tied to the bars
	--]]
        local frame = pvp.frame
        if not frame then return end		
        for i=1,15 do
            local bar = frame.bars[i]
            if bar.func then bar.func = nil end --func is called when a timer finishes
            bar:SetScript("OnMouseDown",nil)
            bar.status:SetScript("OnUpdate",nil)
            bar.status:SetMinMaxValues(0,1)
            bar.status:SetValue(1)
            bar.status.text:SetText("")
            bar.info.text:SetText("")
            bar:Hide()
        end
        pvp:Resize()
    end 
	
--------------------------------------------------------------------------------------------------
    function pvp:Resize()
	--[[
		adjust the size of the main background frame based on how many bars are showing
	--]]
        local frame = pvp.frame
        if not frame then return end
      
        local mode = pvp.mode or "all"      
        if mode ~= "all" then
            if not pvp.settings[mode].override then mode = "all" end
        end
      
        local bars = frame.bars
        local visible = {}
        local barHeight = 0
        local barWidth = 0
        local barCount = 0
        local barSpacing
        local heading = pvp.settings[mode].heading
  
        --determine which bars are visible
        for i=1,15 do
            if bars[i]:IsVisible() then
                barCount = barCount + 1
                tinsert(visible,bars[i])
            end          
        end
  
        if barCount > 0 then 
            barHeight = visible[1]:GetHeight()
            barWidth = visible[1]:GetWidth()
            barSpacing = pvp.settings[mode].bar.padding      
            --resize frame based on how many bars are visible
            for i,p in ipairs(visible) do
                local buf = ((barHeight + barSpacing) * (i - 1)) + heading.size + 1
                p:SetPoint("TOPLEFT", 0, -buf)
            end      
            frame:SetHeight(heading.size + 1 + ((barHeight + barSpacing) * barCount))
            frame:SetWidth(barWidth)
        else
            frame:SetHeight(heading.size)
            frame:SetWidth(heading.width)
        end
    end
 
--------------------------------------------------------------------------------------------------
    function pvp:Redraw(mode,id1,id2)
	--[[
		apply all the appearance options to bars #id1 to #id2 or all bars
		not the most efficient, but fuck it
	--]]
        local frame = pvp.frame
        if not frame then return end
        mode = mode or "all"
		
		pvp:Log("Redraw "..mode.." | "..pvp.mode)
      
        --determine whether or not appearance changes need to apply to the bars currently visible
        local ret = false
        if mode ~= "all" then --a local option changed
            if mode == pvp.mode then --if option matches current mode
                if not pvp.settings[mode].override then ret = true end --if local is set to be used
            else
               ret = true
            end
        else --a global option changed
            if pvp.mode ~= "all" then --a bar set is visible
                if pvp.settings[pvp.mode].override then ret = true end --the mode that is showing the bars is overriding global settings
            --else --no bars are visible
                --return
            end
        end
        if ret then
			pvp:Log("Redraw skipped")
            if pvp.callback then pvp:callback() end
            return
        end
        --
      
        local setting = pvp.settings[mode] 
        --EVERYTHING HERE NEEDS TO BE A SAVED SETTING
        local font = setting.font
        local pos = setting.position
        local texture = setting.texture
        local w = setting.bar.width
        local h = setting.bar.height
        local infoColor = texture.infoColor
        local statusColor = texture.statusColor
 
        --frame stuff
        frame:SetPoint("TOPLEFT",pos.x,pos.y)      
        frame.title:SetFont(font.path,setting.heading.size,"OUTLINE")
        frame.title:SetText(setting.heading.name) 
        frame.background:SetTexture(0,0,0,0.5)
        frame.title:SetPoint("LEFT",10,0)
        frame.title:SetFont("Fonts\\ARIALN.TTF",12,"OUTLINE")
		frame.spy:Show()
		--only show spy button when in battleground
		if pvp.mode == "all" then frame.spy:Hide() else frame.spy:Show() end
      
        --bar stuff
        for i=id1 or 1,id2 or 15 do
            local bar = frame.bars[i]     
            --bar container
            bar:SetWidth(w)
            bar:SetHeight(h)    
            --bar info
            bar.info:SetWidth(w*.2)
            bar.info:SetHeight(h)
            bar.info:SetStatusBarTexture(texture.path)
            bar.info:SetStatusBarColor(infoColor.r,infoColor.g,infoColor.b,infoColor.a)    
            bar.info.text:SetTextColor(font.color.r,font.color.g,font.color.g)
            bar.info.text:SetFont(font.path,font.size,"OUTLINE")    
            --bar status
            bar.status:SetWidth(w*.8)
            bar.status:SetHeight(h)
            bar.status:SetStatusBarTexture(texture.path)
            bar.status:SetStatusBarColor(statusColor.r,statusColor.g,statusColor.b,statusColor.a)
            bar.status.text:SetTextColor(font.color.r,font.color.g,font.color.g)
            bar.status.text:SetFont(font.path,font.size,"OUTLINE")
        end      
        --callback to local battleground stuff to override anything done here
        if pvp.callback then pvp:callback() end
    end

--------------------------------------------------------------------------------------------------
    function pvp:Alpha()
        local frame = pvp.frame
        if not frame then return end
        if frame.mouseover then return end  
      
        local alpha = pvp.settings.alpha
        if UnitAffectingCombat("player") then
            frame:SetAlpha(alpha.combat)
        else
            frame:SetAlpha(alpha.out)
        end
    end
 
--------------------------------------------------------------------------------------------------
    function pvp:ToggleMove(mode)
	--[[
		set main frame to move with mouse
	--]]
        --move with mouse
        local frame = pvp.frame
        if not frame then return end
       
        --make sure the right settings are being accessed
        mode = mode or "all"  
        if mode ~= "all" then
            if not pvp.settings[mode].override then mode="all" end
        end
      
        local pos = pvp.settings[mode].position
      
        if pos.lock then
            frame:SetMovable(false)
            frame:EnableMouse(false)
            frame:RegisterForDrag(nil)
            frame:SetScript("OnDragStart",nil)
            frame:SetScript("OnDragStop",nil)      
        else    
            local x0,y0   
            frame:SetMovable(true)
            frame:EnableMouse(true)
            frame:RegisterForDrag("LeftButton")
            frame:SetScript("OnDragStart",
                function(f)
                    _,_,_,x0,y0 = f:GetPoint() --relative to screen
                    f:StartMoving()
                end
            )
            frame:SetScript("OnDragStop",
                function(f)
                    local _,_,_,x1,y1 = f:GetPoint() --relative to screen
                    f:StopMovingOrSizing()
                  
                    local xdelta = x1 - x0 --horizontal distance moved
                    local ydelta = y1 - y0 --vertical distance moved

                    local xrel = pos.x + xdelta
                    local yrel = pos.y + ydelta
                    pos.x = xrel
                    pos.y = yrel
                end
            )
        end
    end


	
	
--------------------------------------------------------------------------------------------------
    function pvp:DefaultDisplay()
	--[[
		create a display for non-battleground zones consisting of honor and conquest point totals
	--]]
        if pvp.mode ~= "all" then return end
        if not pvp.frame then return end
      
        pvp:Redraw("all") --apply global appearance options
		
		--4.0.1 indeces: 390=Conquest, 392=Honor
        --name,amount,texture,weeklyAmt,weeklyMax,totalMax = GetCurrencyInfo
		local _,hp = GetCurrencyInfo(392)
		local _,cp,_,cpWeekly,cpWeeklyMax = GetCurrencyInfo(390)		
        local honor,conq1,conq2 = pvp:ShowFrames(3)
        local points = pvp.settings.points		
		
		--how to broadcast these bars when clicked
		local click = 
			function(bar)
				local s = bar.status
				local _,limit = s:GetMinMaxValues()
				pvp:Print(s.text:GetText()..": "..s:GetValue().." /"..limit)
			end	         
        
        if points.showHonor then            
            local hp2 = (points.honorMax > 0 and points.honorMax) or hp          
            honor.info.text:SetText(floor(hp/hp2*100 + 0.5).."%")
            honor.status:SetMinMaxValues(0,hp2)
            honor.status:SetValue(hp)
            honor.status.text:SetText("Honor points")			
			honor:SetScript("OnMouseDown",click)
        else
            honor:Hide()
        end        
		
        if points.showWeeklyConq then
            conq1.info.text:SetText(floor(cpWeekly/cpWeeklyMax*100 + 0.5).."%")
            conq1.status:SetMinMaxValues(0,cpWeeklyMax)
            conq1.status:SetValue(cpWeekly)
            conq1.status.text:SetText("Weekly Conquest points")
			conq1:SetScript("OnMouseDown",click)
        else
            conq1:Hide()
        end 
		
        if points.showMaxConq then
            local cp2 = (points.conqMax > 0 and points.conqMax) or cp
            conq2.info.text:SetText(floor(cp/cp2*100 + 0.5).."%")
            conq2.status:SetMinMaxValues(0,cp2)
            conq2.status:SetValue(cp)
            conq2.status.text:SetText("Total Conquest points")
			conq2:SetScript("OnMouseDown",click)			
        else
            conq2:Hide()
        end
      
        pvp:Resize()          
    end


	
--------------------------------------------------------------------------------------------------
    function pvp:ZoneCheck()
	--[[
		called when changing zones, checks name against those stored in bgTable
	--]]
        local zone = GetInstanceInfo()
		if bgTable[zone] then
			pvp:Log("zoned into "..zone)
			zonedinto = zone --keep track of which bg 
			bgTable[zone]:Start()			
		else
			if bgTable[zonedinto] then
				bgTable[zonedinto]:End()
				zonedinto = nil
			end			
			pvp:DefaultDisplay()
		end
    end
	
	
--------------------------------------------------------------------------------------------------	
	function pvp:GetSpecs()
	--[[
		create two tables of official class and specialization names from client
		returns classes table and specs table
	--]]
		if not classes and not specs then --only loop once (ideally)
			classes = {}
			specs = {}
			for i=62,270 do
				local id,spec,_,_,_,_,class = GetSpecializationInfoByID(i)
				if class then
					--class is in uppercase, convert to proper case
					class = (class=="DEATHKNIGHT" and "Death Knight") or strsub(class,1,1)..strlower(strsub(class,2,#(class))) 
					if not tContains(classes,class) then 
						tinsert(classes,class)
						specs[class] = {}
					end
					specs[class][spec] = spec
				end
			end
			sort(classes)
		end
		return classes,specs
	end

	
	
	
--------------------------------------------------------------------------------------------------
    function pvp:CopySettings(to,from)
    --[[
        copy settings in table 'from' to table 'to'
        return table 'to'
    --]]
        if not to then to={} end
        for p in pairs(from) do
            if type(from[p]) == 'table' then
                if not to[p] then to[p] = {} end
                for pp in pairs(from[p]) do
                    to[p][pp] = from[p][pp]
                end
            else
                to[p] = from[p]
            end
        end
        return to
    end
	
	
	
--------------------------------------------------------------------------------------------------
	function pvp:OnInitialize()    
		local saved = saved or {}
		local default = {
			--general frame options        
			alpha = {
					combat = 0.50,
					out = 0.50,
					mouse = 1.00,
					fade = 3,
			},
			points = {
				show = true,
				showHonor = true,
				showWeeklyConq = true,
				showMaxConq = true,
				honorMax = 4000,
				conqMax = 4000,
			},
			spy = {
				localtext = { "%s (%s)", {"name","spec"}},
				globaltext= { "%s (%s)", {"name","altspec"}},
				healersonly = true,
				color = COLORS.gray
			},			
			alt = {
				class = {},
				spec = {}
			},
			broadcast = {
				"INSTANCE_CHAT",
			},

			--global battleground options
			all = {
				position = {
					x = 100,
					y = -500,
					lock = false,
				},
				bar = {
					width = 200,
					height = 25,
					padding = 5,
				},       
				texture = {
					name = "Blizzard",
					path = "Interface\\TargetingFrame\\UI-StatusBar",
					statusColor = COLORS.gray,
					infoColor = COLORS.black,
				},
				font = {
					name = "Arial Narrow",
					path = "Fonts\\ARIALN.TTF",
					size = 14,
					color = COLORS.white,
				},            
				heading = {
					width = 150,
					size = 20,
					name = "PvPness2-beta"
				},
			},
		}		
		
		local classes,specs = pvp:GetSpecs()
		for i,p in pairs(classes) do
			default.alt.class[p] = p
			if not default.alt.spec[p] then default.alt.spec[p]={} end
			for s in pairs(specs[p]) do
				default.alt.spec[p][s] = s
			end
		end

		--wsg options
		default.wsg = pvp:CopySettings({},default.all)
		default.wsg.enabled = true   
		default.wsg.debuff = true
		default.wsg.override = false
		default.wsg.classBars = true
		default.wsg.classNames = false
		default.wsg.faction = true
		default.wsg.clickEFC = {"EFC: %s - %s",{"name","percent"}} 
		
		--load saved settings
        pvp.settings = pvp:CopySettings(default,saved)
	end



	
--------------------------------------------------------------------------------------------------
    function pvp:OnEnable()
        pvp:RegisterChatCommand("p2","SlashCommand")
		pvp:RegisterChatCommand("pvpness2","SlashCommand")
        pvp:RegisterEvent("ZONE_CHANGED_NEW_AREA","ZoneCheck")		
        pvp:RegisterEvent("PLAYER_LOGOUT",
            function()
                saved = pvp.settings
            end
        )       
        main()
        pvp:ZoneCheck()
    end
  
--------------------------------------------------------------------------------------------------
    function pvp:OnDisable()
        saved = pvp.settings
       
        pvp:Reset()
        pvp.frame:Hide()
       
        pvp:UnregisterEvent("ZONE_CHANGED_NEW_AREA")
        pvp:UnregisterEvent("PLAYER_LOGOUT")
    end

	

--------------------------------------------------------------------------------------------------
    function pvp:SlashCommand(args)
	--[[ 
		for testing stuff without being in a battleground 
	--]]
        if not args then
            pvp:Print("debugging/testing function: /p2 battleground")
            return
        end 
        local optionsTable = {}
      
        optionsTable["log"] = pvp.ToggleDebugLog
        optionsTable["debug"] = pvp.ToggleDebugLog
      
        optionsTable["start"] = main
        optionsTable["show"] = main
		
		optionsTable["test"] = function()
			local n = GetNumMapLandmarks() --for ab there should be 7 things
			for i=1,n do
			  local name, description, textureIndex, x, y = GetMapLandmarkInfo(i)
			  print(name)
			end  
		end
        --this will be useful for figuring out how to deal with the minecarts
 
        if optionsTable[args] then optionsTable[args]() else print("no '"..args.."' option found") end
    end
end --eof 